function [idat outp] = fsb_realign_dft2D(idat,param)

% FSB : Realign scans with the discrete fourier transform algorithm
%
% EXAMPLE:
% [idat outp] = fsb_realign_dft2D(idat,1)
%
% INPUT:
% idat:         4-D image data
% param:        precision of registration in voxel
%
% OUTPUT:
% idat:         A realigned 4-D image data volume
% 
% CALLED BY:
% fsb_realign.m
%
% NOTES:
% Requires the dftregistration function copyright
% Manuel Guizar available on matlabcentral.com
% (efficient subpixel registration)
% Citation for his algorithm:
% Manuel Guizar-Sicairos, Samuel T. Thurman, and James R. Fienup,
% "Efficient subpixel image registration algorithms," Opt. Lett. 33,
% 156-158 (2008).
%
% Copyright 2010 MPI for Biological Cybernetics
% Author: Steffen Stoewer
% License:GNU GPL, no express or implied warranties
% 
% $Revision 1.0
%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Check if second input is provided
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if nargin<2
    param = 0.01;
end

reafig = waitbar(0,'Realigning ...');
dim = size(idat);
midat = mean(idat,4);

%~~~~~~~~~~~~~~
% Go over slices
%~~~~~~~~~~~~~~

for y=1:dim(3);
    idat1 = single(squeeze(midat(:,:,y)));
    waitbar (y/dim(3));
    %~~~~~~~~~~~~~~
    % Go over time points
    %~~~~~~~~~~~~~~
    for x = 1:dim(4);
        idatx = single(squeeze(idat(:,:,y,x)));
        [output output2] = dftregistration(fft2(idat1),fft2(idatx),param);
        outp.output(x,:,y) = output;
        outp.output2(:,:,y,x) = abs(ifft2(output2));
    end

end
idat = int16(outp.output2);
close (reafig);

end
